package listener;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

//统计网络在线人数，统计session
public class onlineCount implements HttpSessionListener {


    //创建session监听
    //创建一次session就会触发一次此事件
    @Override
    public void sessionCreated(HttpSessionEvent se) {
        ServletContext ctx= se.getSession().getServletContext();

        System.out.println(se.getSession().getId());

        int count =(int) ctx.getAttribute("OnlineCount")+1;

        if(count==0)
        {
            count= 1;
        } else{
            count ++;
        }

        ctx.setAttribute("OnlineCount",count);
    }

    //销毁监听
    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        ServletContext ctx= se.getSession().getServletContext();

        Integer count = (Integer) ctx.getAttribute("OnlineCount");

        if(count==null)
        {
            count= new Integer(1);
        } else{
            int ct = count.intValue();

            count = new Integer(ct-1);
        }

        ctx.setAttribute("OnlineCount",count);
    }
}
